using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace demowebsocket
{
    public class SocketMiddleware
    {
        private RequestDelegate next;
        private IWebStocketHandler WebStocketHandler;
        private ILogger<SocketMiddleware> _logger;
        public SocketMiddleware(RequestDelegate _next,IWebStocketHandler webStocketHandler,ILogger<SocketMiddleware> _logger)
        {
            this.next = _next;
            this.WebStocketHandler = webStocketHandler;
            this._logger = _logger;
        }


   
        public async Task InvokeAsync(HttpContext context)
        {

            try
            {
                if (!context.WebSockets.IsWebSocketRequest)
                {
                    await next(context);
                }
                else
                {
                    
                    
                    var socket = await context.WebSockets.AcceptWebSocketAsync();
                    //触发服务器添加socket client;
                    await WebStocketHandler.OnClientConnect(socket);

                    byte[] buf = new byte[1024 * 10];
                    
                    
                    while (socket.State==WebSocketState.Open)
                    {
                        // var socketFinishedTcs = new TaskCompletionSource<object>();
                        //
                        // BackgroundSocketProcessor.AddSocket(webSocket, socketFinishedTcs);
                        //
                        // await socketFinishedTcs.Task;
                        var rs = await  socket.ReceiveAsync(new ArraySegment<byte>(buf), CancellationToken.None);
                  
                        switch (rs.MessageType)
                        {
                            case  WebSocketMessageType.Close:
                                await WebStocketHandler.OnClientClose(socket);
                                break;
                            case  WebSocketMessageType.Binary:
                                break;
                            case  WebSocketMessageType.Text:
                                await WebStocketHandler.ReceiveMessageText(socket, rs.Count, buf);
                                break;
                           
                        }
                  
                    }

                }
            }
            catch (Exception e)
            {
                
                _logger.LogError(e.Message);
                
            }
          
            
        }
    }
}